package com.waverider.promotion.biz.manager.impl;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.iacrqq.util.StringUtil;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Order;
import com.taobao.api.domain.Trade;
import com.taobao.api.request.TradeGetRequest;
import com.taobao.api.response.TradeGetResponse;
import com.waverider.promotion.biz.dao.OrderDAO;
import com.waverider.promotion.biz.manager.ItemManager;
import com.waverider.promotion.biz.manager.OrderManager;
import com.waverider.promotion.biz.manager.ShopManager;
import com.waverider.promotion.domain.OrderDO;
import com.waverider.promotion.domain.PromotionDO;
import com.waverider.promotion.domain.ShopDO;
import com.waverider.promotion.enums.OrderStatusEnum;
import com.waverider.promotion.model.OrderQueryModel;
import com.waverider.promotion.model.ResultModel;

public class OrderManagerImpl implements OrderManager
{

	private static final Log logger = LogFactory.getLog(OrderManagerImpl.class);
	
	private OrderDAO orderDAO;
	private ShopManager shopManager;
	private ItemManager itemManager;
	private TaobaoClient taobaoClient;
	
	@Override
	public void add(OrderDO order)
	{
		orderDAO.insert(order);
	}
	
	@Override
	public void addOrUpdateOrder(OrderDO order)
	{
		OrderDO o = orderDAO.queryByOrderId(order.getOrderId());
		
		if(o == null)
		{
			orderDAO.insert(order); 
		}
		else
		{
			order.setId(o.getId());
			orderDAO.update(order);
		}
	}

	@Override
	public boolean update(OrderDO order)
	{
		return orderDAO.update(order);
	}

	@Override
	public OrderDO getByBuyerAndItemId(Long buyer, Long itemId)
	{
		return orderDAO.queryByBuyerAndPromotion(buyer, itemId);
	}
	
	@Override
	public OrderDO getOrderByOrderId(Long orderId)
	{
		return orderDAO.queryByOrderId(orderId);
	}
	
	@Override
	public ResultModel<OrderDO> getOrderList(OrderQueryModel queryModel)
	{
		return ResultModel.buildResultModel(queryModel, orderDAO.query(queryModel), orderDAO.count(queryModel));
	}

	@Override
	public boolean delete(Long id)
	{
		return orderDAO.delete(id);
	}
	
	@Override
	public void syncTrade(Long sellerId, Long tradeId)
	{
		try
		{
			ShopDO shop = shopManager.getBySellerId(sellerId);
			Trade trade = _get_trade_from_taobao_(shop.getSessionKey(), tradeId);
			
			List<Order> orderList = trade.getOrders();
			
			for(Order order : orderList)
			{
				PromotionDO promotion = itemManager.getPromotionByGoodsId(order.getNumIid());
				if(promotion == null)
				{
					logger.warn(new StringBuilder("Order is not promotion, goodsId:").append(order.getNumIid()));
					continue;
				}
				
				OrderDO o = new OrderDO();
				o.setOrderId(order.getOid());
				o.setBuyerNick(order.getBuyerNick());
				// 实付金额
				o.setFree(new BigDecimal(order.getPayment()));
				o.setGoodsId(order.getNumIid());
				o.setGoodsName(order.getTitle());
				o.setGoodsPicURL(order.getPicPath());
				o.setPrice(new BigDecimal(order.getPrice()));
				o.setQuantity(order.getNum());
				o.setSellerNick(order.getSellerNick());
				o.setSellerId(sellerId);
				o.setShopId(shop.getShopId());
				
				OrderStatusEnum status = _get_order_status_(order.getStatus());
				
				if(status == null)
				{
					throw new RuntimeException(new StringBuilder("Unknown order status:").append(order.getStatus()).toString());
				}
				o.setStatus(status.value());
				o.setPromotion(promotion.getId());
				
				addOrUpdateOrder(o);
				
				// 只有付款才去同步
				if(o.getStatus().intValue() == OrderStatusEnum.ORDER_STATUS_WAIT_BUYER_PAY.value())
				{
					itemManager.syncPromotion(shop.getSessionKey(), promotion, o);
				}
			}
		}
		catch(ApiException e)
		{
			logger.error(e);
		}
	}
	
	private OrderStatusEnum _get_order_status_(String status)
	{
		for(OrderStatusEnum e : OrderStatusEnum.values())
		{
			if(StringUtil.equals(status, e.key()))
			{
				return e;
			}
		}
		
		return null;
	}
	
	private Trade _get_trade_from_taobao_(String sessionKey, Long tradeId) throws ApiException
	{
		TradeGetRequest request = new TradeGetRequest();
		request.setFields("seller_nick,buyer_nick,status,orders.title,orders.pic_path,orders.price,orders.num,orders.num_iid,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee");
		request.setTid(tradeId);
		TradeGetResponse response = taobaoClient.execute(request , sessionKey);
		
		return response.getTrade();
	}
	
	public void setOrderDAO(OrderDAO orderDAO)
	{
		this.orderDAO = orderDAO;
	}
	
	public void setShopManager(ShopManager shopManager)
	{
		this.shopManager = shopManager;
	}
	
	public void setItemManager(ItemManager itemManager)
	{
		this.itemManager = itemManager;
	}
	
	public void setTaobaoClient(TaobaoClient taobaoClient)
	{
		this.taobaoClient = taobaoClient;
	}

}
